import React, { useState, useEffect } from 'react';
import './EditNicknameModal.css';

interface EditNicknameModalProps {
  isOpen: boolean;
  currentNickname: string;
  onClose: () => void;
  onSave: (newNickname: string) => void;
}

const EditNicknameModal: React.FC<EditNicknameModalProps> = ({
  isOpen,
  currentNickname,
  onClose,
  onSave,
}) => {
  const [nickname, setNickname] = useState(currentNickname);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setNickname(currentNickname);
    }
  }, [isOpen, currentNickname]);

  const handleSave = async () => {
    if (!nickname.trim()) {
      alert('昵称不能为空');
      return;
    }

    if (nickname.trim() === currentNickname) {
      onClose();
      return;
    }

    setIsLoading(true);
    try {
      await onSave(nickname.trim());
      onClose();
    } catch (error) {
      console.error('修改昵称失败:', error);
      alert('修改昵称失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSave();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="edit-nickname-modal-overlay">
      <div className="edit-nickname-modal">
        <div className="modal-header">
          <button className="cancel-btn" onClick={onClose}>
            取消
          </button>
          <h3 className="modal-title">修改群昵称</h3>
          <button
            className="save-btn"
            onClick={handleSave}
            disabled={isLoading || !nickname.trim()}
          >
            {isLoading ? '保存中...' : '保存'}
          </button>
        </div>

        <div className="modal-content">
          <div className="input-group">
            <label className="input-label">群昵称</label>
            <input
              type="text"
              value={nickname}
              onChange={e => setNickname(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入群昵称"
              className="nickname-input"
              maxLength={20}
              autoFocus
            />
            <div className="char-count">{nickname.length}/20</div>
            <div className="input-tip">此昵称仅在此群聊中显示</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EditNicknameModal;
